<?php
$taskName = $_POST['TaskName'] ?? null;
$taskContent = $_POST['TaskContent'] ?? null;
if (empty($taskName)) {
    echo "任务名称不能为空<br />";
    echo "<a href='javascript:history.go(-1);'>返回上一页</a>";
    die();
}
if (!(mb_strlen($taskName) >= 4 && mb_strlen($taskName) <= 50)) {
    echo "任务名称4到50个字<br />";
    echo "<a href='javascript:history.go(-1);'>返回上一页</a>";
    die();
}

if (!(mb_strlen($taskContent) >= 20 && mb_strlen($taskContent) <= 2000)) {
    echo "任务内容20到2000个字<br />";
    echo "<a href='javascript:history.go(-1);'>返回上一页</a>";
    die();
}

$dsn = "sqlsrv:Server=localhost;Database=Task";
$db = new PDO($dsn, "sa", "123456");

// 判断任务是否存在
$selectSql = "select * from Task where TaskName='{$taskName}' ";
$statement = $db->query($selectSql);
$taskInfo = $statement->fetch(PDO::FETCH_ASSOC);
if ($taskInfo) {
    echo "任务已经存在了<br />";
    echo "<a href='javascript:history.go(-1);'>返回上一页</a>";
    die();
}

$sql = "insert into Task (TaskName, TaskContent) values ('{$taskName}','{$taskContent}')";
$result = $db->exec($sql);
if ($result) {
    echo "增加任务成功<br />";
    echo "<a href='task_list.php'>返回列表页面</a>";
} else {
    echo "增加任务失败，错误信息为：<pre>{$db->errorInfo()[2]}</pre>";
    echo "<a href='javascript:history.go(-1);'>返回上一页</a>";
}